<template>
  <div class="swiper-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">轮播图管理</span>
        </div>
      </div>
      <h1 class="page-title">轮播图管理</h1>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <router-link to="/swiper/add" class="v-button primary">
        <i class="iconfont icon-add"></i> 添加轮播图
      </router-link>

      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="search-input">
          <i class="iconfont icon-search"></i>
          <input
            v-model="searchQuery"
            placeholder="搜索标题/副标题"
            @keyup.enter="handleSearch"
          />
          <i
            v-if="searchQuery"
            class="iconfont icon-close"
            @click="handleSearchClear"
          ></i>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <div class="filter-group">
        <label class="filter-label">显示状态</label>
        <BaseSelect
          v-model="filters.is_visible"
          :options="visibleOptions"
          placeholder="请选择状态"
        />
      </div>

      <button class="v-button primary" @click="applyFilters">
        <i class="iconfont icon-filter-records"></i> 筛选
      </button>
      <button class="v-button outline" @click="resetFilters">
        <i class="iconfont icon-reset"></i> 重置
      </button>
    </div>

    <!-- 轮播图表格 -->
    <div class="v-container">
      <table class="v-table">
        <thead>
          <tr>
            <th width="80">ID</th>
            <th>图片</th>
            <th>标题</th>
            <th>副标题</th>
            <th>链接</th>
            <th width="100">排序</th>
            <th width="100">状态</th>
            <th width="180">创建时间</th>
            <th width="180">更新时间</th>
            <th width="200">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="swiper in filteredSwiperList" :key="swiper.id">
            <td>{{ swiper.id }}</td>
            <td>
              <div class="swiper-image">
                <img :src="swiper.image_url" :alt="swiper.title" @click="previewImage(swiper.image_url)" />
              </div>
            </td>
            <td>{{ swiper.title }}</td>
            <td>{{ swiper.subtitle || "-" }}</td>
            <td>
              <a :href="swiper.link" target="_blank" class="link-text">
                {{ truncateLink(swiper.link) }}
              </a>
            </td>
            <td>{{ swiper.sort_order }}</td>
            <td>
              <span
                @click="toggleVisible(swiper)"
                :class="[
                  'status-badge',
                  swiper.is_visible === '1' ? 'active' : 'inactive',
                ]"
              >
                {{ swiper.is_visible === "1" ? "显示" : "隐藏" }}
              </span>
            </td>
            <td>{{ formatTimestamp(swiper.created_at) }}</td>
            <td>{{ formatTimestamp(swiper.updated_at) }}</td>
            <td>
              <div class="control">
                <router-link :to="'/swiper/edit/' + swiper.id" class="v-button">
                  <i class="iconfont icon-edit"></i> 编辑
                </router-link>
                <button class="v-button danger" @click="confirmDelete(swiper)">
                  <i class="iconfont icon-delete1"></i> 删除
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="!loading && swiperList.length === 0">
            <td colspan="10" class="empty-row">
              <i class="iconfont icon-empty"></i>
              {{ searchQuery ? "没有找到匹配的轮播图" : "暂无数据" }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="showPreview" class="image-preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="previewImageUrl" alt="预览图" />
        <button class="close-btn" @click="closePreview">
          <i class="iconfont icon-close"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import BaseSelect from "@/components/BaseSelect.vue";

const router = useRouter();

// 数据
const swiperList = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const showPreview = ref(false);
const previewImageUrl = ref("");

// 筛选条件
const filters = ref({
  is_visible: "",
});

// 状态选项
const visibleOptions = ref([
  { value: "1", text: "显示" },
  { value: "0", text: "隐藏" },
]);

// 获取轮播图列表
const fetchSwipers = async () => {
  try {
    loading.value = true;
    const res = await get("/swiper/list");
    if (res.code === 200) {
      swiperList.value = res.data || [];
    } else {
      vToast.error(res.msg || "获取轮播图列表失败");
    }
  } catch (error) {
    vToast.error("获取轮播图列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 搜索
const handleSearch = () => {
  fetchSwipers();
};

const handleSearchClear = () => {
  searchQuery.value = "";
  fetchSwipers();
};

// 筛选
const applyFilters = () => {
  fetchSwipers();
};

const resetFilters = () => {
  filters.value = {
    is_visible: "",
  };
  searchQuery.value = "";
  fetchSwipers();
};

// 过滤后的轮播图列表
const filteredSwiperList = computed(() => {
  let list = [...swiperList.value];
  
  // 应用搜索条件
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    list = list.filter(item => 
      item.title.toLowerCase().includes(query) || 
      (item.subtitle && item.subtitle.toLowerCase().includes(query))
    );
  }
  
  // 应用状态筛选
  if (filters.value.is_visible !== "") {
    list = list.filter(item => item.is_visible === filters.value.is_visible);
  }
  
  return list;
});

// 切换显示状态
const toggleVisible = (swiper) => {
  const newStatus = swiper.is_visible === '1' ? '0' : '1';
  const action = newStatus === '1' ? "显示" : "隐藏";

  vConfirm({
    message: `确定要${action}轮播图【${swiper.title}】吗？`,
    onConfirm: async () => {
      try {
        const res = await post("/swiper/edit", {
          id: swiper.id,
          is_visible: newStatus,
          title: swiper.title,
          subtitle: swiper.subtitle,
          image_url: swiper.image_url,
          link: swiper.link,
          sort_order: swiper.sort_order
        });

        if (res.code === 200) {
          vToast.success(`${action}轮播图成功`);
          fetchSwipers();
        } else {
          vToast.error(res.msg || `${action}轮播图失败`);
        }
      } catch (error) {
        vToast.error(`${action}轮播图失败`);
        console.error(error);
      }
    },
  });
};

// 删除确认
const confirmDelete = (swiper) => {
  vConfirm({
    message: `确定要删除轮播图【${swiper.title}】吗？`,
    onConfirm: () => deleteSwiper(swiper.id),
  });
};

const deleteSwiper = async (id) => {
  try {
    const res = await post("/swiper/delete", { id });

    if (res.code === 200) {
      vToast.success("轮播图删除成功");
      fetchSwipers();
    } else {
      vToast.error(res.msg || "删除失败");
    }
  } catch (error) {
    vToast.error("删除失败");
    console.error(error);
  }
};

// 图片预览
const previewImage = (url) => {
  previewImageUrl.value = url;
  showPreview.value = true;
};

const closePreview = () => {
  showPreview.value = false;
  previewImageUrl.value = "";
};

// 截断链接显示
const truncateLink = (link) => {
  if (!link) return "-";
  if (link.length > 30) {
    return link.substring(0, 15) + "..." + link.substring(link.length - 10);
  }
  return link;
};

// 初始化加载数据
onMounted(() => {
  fetchSwipers();
});
</script>

<style scoped lang="less">
.swiper-page {
  .breadcrumb {
    margin-bottom: 20px;
  }

  .action-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;

    .search-wrapper {
      flex: 1;
      max-width: 300px;
      margin-left: auto;

      .search-input {
        position: relative;
        display: flex;
        align-items: center;
        background: var(--v-card-bg);
        border-radius: var(--v-card-radius);
        border: 1px solid var(--v-border-color);
        padding: 0 10px;
        height: 36px;

        i {
          color: var(--v-text-light);
          margin-right: 8px;
        }

        input {
          flex: 1;
          border: none;
          background: transparent;
          outline: none;
          color: var(--v-text);

          &::placeholder {
            color: var(--v-text-light);
          }
        }

        .icon-close {
          cursor: pointer;
          margin-left: 8px;

          &:hover {
            color: var(--v-danger);
          }
        }
      }
    }
  }

  .filter-bar {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    flex-wrap: wrap;

    .filter-group {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        font-size: 14px;
        color: var(--v-text-darker);
        white-space: nowrap;
      }
    }
  }

  .v-container {
    background-color: var(--v-card-bg);
    border-radius: var(--v-card-radius);
    box-shadow: var(--v-shadow);
    padding: 20px;
    margin-top: 30px;
    transition: all 0.3s;
  }

  .v-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid var(--v-border-color);
    }

   

    tr:hover {
      background-color: #f9f9f9;
    }
  }

  .swiper-image {
    width: 80px;
    height: 50px;
    overflow: hidden;
    border-radius: 4px;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
      
      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .link-text {
    color: var(--v-theme);
    text-decoration: none;
    word-break: break-all;
    
    &:hover {
      text-decoration: underline;
    }
  }

  .control {
    display: flex;
    align-items: center;
    gap: 8px;

    .v-button {
      padding: 0px 8px;
      font-size: 12px;
      min-width: auto;
      height: 32px;
      line-height: 32px;
      background: var(--v-background-pure);
      color: var(--v-sidebar-background);
      border: var(--v-sidebar-background) 1px solid;

      i {
        margin-right: 4px;
      }

      &.danger {
        color: var(--v-danger);
        border-color: var(--v-danger);
      }
    }
  }

  .empty-row {
    text-align: center;
    padding: 20px;
    color: var(--v-text-light);

    .iconfont {
      font-size: 48px;
      margin-bottom: 10px;
      display: block;
    }
  }

  /* 状态标签 */
  .status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;

    &.active {
      background-color: #e6f7e6;
      color: #52c41a;
    }

    &.inactive {
      background-color: #fff1f0;
      color: #f5222d;
    }
  }

  /* 图片预览模态框 */
  .image-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    
    .preview-content {
      position: relative;
      max-width: 90%;
      max-height: 90%;
      
      img {
        max-width: 100%;
        max-height: 80vh;
        border-radius: 8px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
      }
      
      .close-btn {
        position: absolute;
        top: -40px;
        right: 0;
        background: none;
        border: none;
        color: white;
        font-size: 24px;
        cursor: pointer;
        
        &:hover {
          color: var(--v-theme);
        }
      }
    }
  }
}
</style>